package com.hns.tool.pub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http传输数据
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class HttpRequestProxy {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpRequestProxy.class);
    
    /**
     * 连接超时
     */
    private static int    connectTimeOut  = 5000;
    
    /**
     * 读取数据超时
     */
    private static int    readTimeOut     = 10000;
    
    /**
     * 请求编码
     */
    private static String requestEncoding = "UTF-8";
    
    /**
     * post发送json字符串格式的请求(普通http链接)
     * @param requestUrl 发送url
     * @param jsonStr json格式字符串
     * @return 返回消息封装的json对象
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static JSONObject doHttpPost(String requestUrl, String jsonStr) {
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            httpUrlConn.setRequestMethod("POST");  
  
            // 当有数据需要提交时  
            if (null != jsonStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(jsonStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            ce.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return jsonObject;  
    }  
    
    /**
     * 将map内容转化指定格式字符串，封装为http请求发送到指定url
     * @param reqUrl url
     * @param parameters 参数map
     * @return 返回的消息转化的字符串
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    //TODO
    public static String doPost(String reqUrl, Map parameters) {
        HttpURLConnection conUrl = null;
        String responseContent = null;
        try {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(), HttpRequestProxy.requestEncoding));
                params.append("&");
            }
            
            if (params.length() > 0) {
                params = params.deleteCharAt(params.length() - 1);
            }
            logger.info(reqUrl);
            URL url = new URL(reqUrl);
            conUrl = (HttpURLConnection) url.openConnection();
            conUrl.setRequestMethod("POST");
            conUrl.setConnectTimeout(getConnectTimeOut()); // （单位：毫秒）jdk1.5换成这个,连接超时
            conUrl.setReadTimeout(getConnectTimeOut()); // （单位：毫秒）jdk
                                                        // 1.5换成这个,读操作超时
            conUrl.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            conUrl.getOutputStream().write(b, 0, b.length);
            conUrl.getOutputStream().flush();
            conUrl.getOutputStream().close();
            
            InputStream in = conUrl.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, getRequestEncoding()));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            System.err.println("网络故障");
            e.printStackTrace();
        } finally {
            if (conUrl != null) {
                conUrl.disconnect();
            }
        }
        return responseContent;
    }
    
    /**
     * post发送json字符串格式的请求(https安全链接)
     * @param requestUrl 请求url
     * @param jsonStr json格式字符串
     * @return 返回消息封装的json对象
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static JSONObject doHttpsPost(String requestUrl, String jsonStr) {
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            httpUrlConn.setRequestMethod("POST");  
  
            // 当有数据需要提交时  
            if (null != jsonStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(jsonStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            ce.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return jsonObject;  
    }  
    
    /**
     * 获取连接超时毫秒数
     * @return 连接超时(毫秒)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static int getConnectTimeOut() {
        return HttpRequestProxy.connectTimeOut;
    }
    
    /**
     * 读取数据超时毫秒数
     * @return 读取数据超时(毫秒)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static int getReadTimeOut() {
        return HttpRequestProxy.readTimeOut;
    }
    
    /**
     * 获取请求编码
     * @return 请求编码
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static String getRequestEncoding() {
        return requestEncoding;
    }
    
    /**
     * 设置连接超时(毫秒)
     * @param connectTimeOut 设置连接超时(毫秒)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static void setConnectTimeOut(int connectTimeOut) {
        HttpRequestProxy.connectTimeOut = connectTimeOut;
    }
    
    /**
     * 设置读取数据超时(毫秒)
     * @param readTimeOut 读取数据超时(毫秒)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static void setReadTimeOut(int readTimeOut) {
        HttpRequestProxy.readTimeOut = readTimeOut;
    }
    
    /**
     * 设置请求编码
     * @param requestEncoding 请求编码
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public static void setRequestEncoding(String requestEncoding) {
        HttpRequestProxy.requestEncoding = requestEncoding;
    }
    
    public static void main(String[] args) {
        
    }
    
}
